<?php
require('../vendor/autoload.php');

use BitWasp\Bitcoin\Key\PrivateKeyFactory;
use BitWasp\Bitcoin\Script\ScriptFactory;
use BitWasp\Bitcoin\Address\ScriptHashAddress;
use BitWasp\Bitcoin\Transaction\TransactionOutput;
use BitWasp\Bitcoin\Transaction\Factory\Signer;
use BitWasp\Bitcoin\Transaction\Factory\SignData;
use BitWasp\Bitcoin\Serializer\Transaction\TransactionSerializer;
use BitWasp\Bitcoin\Transaction\TransactionFactory;
use BitWasp\Bitcoin\Address\AddressCreator;
use BitWasp\Bitcoin\Network\NetworkFactory;
use BtcTool\Credential;
use BtcTool\Client;

function fund($addr,$amount){
  $client = new Client('http://user:123456@127.0.0.1:18443');
  $txid = $client->exec('sendtoaddress',$addr,$amount)->result;
  $client->exec('generate',6);
  $tx = $client->exec('getrawtransaction',$txid,true)->result;
  foreach($tx->vout as $txo){
    if(in_array($addr,$txo->scriptPubKey->addresses)){
      return [
        'txid'=>$txid,
        'vout'=>$txo->n,
        'value'=>$txo->value,
        'script'=>ScriptFactory::fromHex($txo->scriptPubKey->hex)
      ];
    }
  }
}

function spend($utxo,$spenders,$shop,$redeemScript){
  $val = intval($utxo['value']*1e8 - 10000);

  $tx = TransactionFactory::build()
          ->input($utxo['txid'],$utxo['vout'])
                  ->output($val,$shop->p2pkh->getScriptPubKey())
                  ->get();

  $signer = new Signer($tx);
  $signData = new SignData();
  $signData->p2sh($redeemScript);
  $lock = new TransactionOutput($utxo['value'],$utxo['script']);
  foreach($spenders as $spender){
    $signer->sign(0,$spender->prv,$lock,$signData);
  }

  $serializer = new TransactionSerializer();
  $raw = $serializer->serialize($signer->get());
  //echo $raw->getHex() . PHP_EOL;
  return $raw->getHex();
}

function decode($rawtx){
  $client = new Client('http://user:123456@127.0.0.1:18443');
  $ret = $client->exec('decoderawtransaction',$rawtx);
  var_dump($ret);
}

function confirm($rawtx){
  $client = new Client('http://user:123456@127.0.0.1:18443');
  $txid = $client->exec('sendrawtransaction',$rawtx)->result;
  $client->exec('generate',6);
  return $txid;
}

$tommy = Credential::new();
$jerry = Credential::new();
$shop = Credential::new();

$redeemScript = ScriptFactory::scriptPubKey()->multisig(2,[$tommy->pub,$jerry->pub]);
$p2sh = new ScriptHashAddress($redeemScript->getScriptHash());
$addr = $p2sh->getAddress(NetworkFactory::bitcoinRegtest());

$utxo = fund($addr,10);
//var_dump($utxo);
$rawtx = spend($utxo,[$tommy,$jerry],$shop,$redeemScript);
//decode($rawtx);               
$txid = confirm($rawtx);
echo 'txid => ' . $txid . PHP_EOL;
                